<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-alert title="提示：只允许为三级分类设置相关参数或属性！" type="warning" show-icon :closable="false">
      </el-alert>
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader v-model="cateSelectkey" :options="AllCateList" :props="cateProps" @change="cateHandleChange"
            clearable>
          </el-cascader>
        </el-col>
      </el-row>

      <!-- Tag标签页 -->
      <el-tabs v-model="paramsActiveName" @tab-click="parHandleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="small" :disabled="isButActive" @click="addParmDialogVisible = true">添加参数
          </el-button>
          <el-table :data="manyTagData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag closable v-for="(item, index1) in scope.row.attr_vals" :key="index1" @close="handleClose(scope.row,index1)">
                  {{item}}
                </el-tag>
                <!-- new tag input框 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <!-- new tag 按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showTagInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑
                </el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="DeleteParms(scope.row.attr_id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="small" :disabled="isButActive" @click="addParmDialogVisible = true">添加属性
          </el-button>
          <el-table :data="onlyTagData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag closable v-for="(item, index1) in scope.row.attr_vals" :key="index1">
                  {{item}}
                </el-tag>
                <!-- new tag input框 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <!-- new tag 按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showTagInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑
                </el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="DeleteParms(scope.row.attr_id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog :title="'添加' + addTitleText" :visible.sync="addParmDialogVisible" width="40%"
      @close="addParamDialogClose">
      <el-form :model="addParmForm" :rules="addParmFormRules" ref="addParmFormRef" label-width="100px">
        <el-form-item :label="this.addTitleText" prop="attr_name">
          <el-input v-model="addParmForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParmDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog :title="'添加' + addTitleText" :visible.sync="editParmDialogVisible" width="40%"
      @close="editParamDialogClose">
      <el-form :model="editParmForm" :rules="editParmFormRules" ref="editParmFormRef" label-width="100px">
        <el-form-item :label="this.addTitleText" prop="attr_name">
          <el-input v-model="editParmForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParmDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      paramsActiveName: 'many',
      AllCateList: [],
      //级联选择框选中的值id
      cateSelectkey: [],

      cateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      manyTagData: [],
      onlyTagData: [],

      addParmDialogVisible: false,
      //添加参数表单数据
      addParmForm: {
        attr_name: '',
      },
      //添加参数表单规则
      addParmFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },

      //修改参数表单数据
      editParmDialogVisible: false,
      editParmForm: {},
      editParmFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
    }
  },

  methods: {
    async getAllCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('请求服务器失败！')
      }
      this.AllCateList = res.data
    },
    //获取参数列表
    async getParamsList() {
      if (this.cateSelectkey.length === 3) {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          { params: { sel: this.paramsActiveName } }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('请求服务器失败，无法获取参数列表！')
        }
        //将attr_vals的值转化为数组
        res.data.forEach((item) => {
          //判断attr_vals的值是否为空，为空则不需要split分割
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          item.inputVisible = false
          item.inputValue = ''
        })
        console.log('resdata',res.data)
        if (this.paramsActiveName === 'many') {
          this.manyTagData = res.data
        } else {
          this.onlyTagData = res.data
        }
      }else{
        this.cateSelectkey = []
        this.manyTagData = []
        this.onlyTagData = []
      }
      
    },

    cateHandleChange() {
      this.getParamsList()
    },
    parHandleClick() {
      this.getParamsList()
    },
    //添加参数
    addParams() {
      this.$refs.addParmFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addParmForm.attr_name,
            attr_sel: this.paramsActiveName,
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('请求服务器失败，无法添加此参数！')
        }
        this.$message.success('添加成功')
        this.addParmDialogVisible = false
        this.getParamsList()
      })
    },
    addParamDialogClose() {
      this.$refs.addParmFormRef.resetFields()
    },
    //展示修改参数对话框
    async showEditDialog(attr_id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        {
          params: { attr_sel: this.paramsActiveName },
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('请求服务器失败')
      }
      // console.log(res.data)
      this.editParmForm = res.data
      this.editParmDialogVisible = true
    },
    //修改参数
    editParams() {
      this.$refs.editParmFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editParmForm.attr_id}`,
          {
            attr_name: this.editParmForm.attr_name,
            attr_sel: this.paramsActiveName,
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('请求服务器失败，无法修改此参数信息')
        }
        this.$message.success('修改成功')
        this.getParamsList()
        this.editParmDialogVisible = false
      })
    },
    editParamDialogClose() {
      this.$refs.editParmFormRef.resetFields()
    },

    //删除参数
    async DeleteParms(attr_id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((error) => error)
      if (confirmResult !== 'confirm') {
        return this.$message.warning('取消了删除')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attr_id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('请求服务器失败，无法删除')
      }
      this.$message.success('删除成功')
      this.getParamsList()
    },
    //回车或者失焦时触发
    handleInputConfirm(row){
      //输入的是空，或者只有空格是退出
      if(row.inputValue.trim().length === 0){
        row.inputVisible = !row.inputVisible
        row.inputValue = ''
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = !row.inputVisible
      this.saveAttrVals(row)

    },
    //保存attr_vals的值
    async saveAttrVals(row){
      const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if(res.meta.status !== 200){
        return this.$message.error("请求服务器失败！")
      }
      this.$message.success('操作成功')
    },
    // 展示文本输入框
    showTagInput(row){
      row.inputVisible = !row.inputVisible
      //input框自动获取焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
      console.log('row',row)
    },
    //删除参数选项
    handleClose(row,index1){
      row.attr_vals.splice(index1,1)
      this.saveAttrVals(row)
    }
  },

  computed: {
    isButActive() {
      if (this.cateSelectkey.length === 3) {
        return false
      }
      return true
    },
    //分类id
    cateId() {
      if (this.cateSelectkey.length === 3) {
        return this.cateSelectkey[2]
      }
      return null
    },
    addTitleText() {
      if (this.paramsActiveName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    },
  },

  created() {
    this.getAllCateList()
  },
}
</script>

<style lang="less" scoped>
.el-row {
  margin-top: 20px;
  font-size: 18px;
}
.el-cascader {
  width: 20%;
}
.el-tag {
  margin: 15px;
}
.input-new-tag{
  width: 120px;
}
</style>